package com.chatplus.application.service.wxmp.handler;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.account.WechatUserEntity;
import com.chatplus.application.enumeration.WechatUserStatusEnum;
import com.chatplus.application.service.account.WechatUserService;
import com.chatplus.application.service.wxmp.impl.WeChatMpService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 取消关注处理器
 *
 * @author chj
 */
@Component
public class UnsubscribeHandler extends AbstractHandler {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(UnsubscribeHandler.class);
    private final WechatUserService wechatService;

    public UnsubscribeHandler(WeChatMpService weChatMpService, WechatUserService wechatService) {
        super(weChatMpService);
        this.wechatService = wechatService;
    }

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String openId = wxMessage.getFromUser();
        LOGGER.message("取消关注用户").context("OPENID", openId).info();
        WechatUserEntity weChatUser = this.wechatService.getOneByOpenidAndAppId(wxMessage.getFromUser(), wxMessage.getToUser());
        if (weChatUser != null) {
            weChatUser.setStatus(WechatUserStatusEnum.UNFOLLOW);
            this.wechatService.updateById(weChatUser);
        }
        return null;
    }

}
